<template>
	<div class="recommend-container">
		<el-row>
			<div class="page-header">
				<div class="page-header-heading">
					<div class="page-header-heading-left">
						<span class="page-header-heading-title">
							推荐资源
						</span>
					</div>
				</div>

				<div class="page-header-content">
					<span>欢迎推荐你想分享的资源，推荐成功后将为你推送同时获得积分奖励💰</span>
				</div>
			</div>
		</el-row>
		<el-row>
			<div class="page-content">
				<el-card class="box-card">
					<el-form class="form-main" ref="recommendForm" label-width="100px" label-position="right"
						:model="recommendData" :rules="rules">
						<el-form-item label="名称" prop="title">
							<el-input class="form-main-input" v-model="recommendData.title"
								placeholder="资源名称或网站名字,不超过15个字">
							</el-input>
						</el-form-item>
						<el-form-item label="描述" prop="description">
							<el-input class="form-main-input" v-model="recommendData.description"
								placeholder="用一句话简单介绍该资源主要内容,不超过30个字"></el-input>
						</el-form-item>

						<el-form-item label="链接" prop="link">
							<el-input class="form-main-input" v-model="recommendData.link" placeholder="该资源的链接">
							</el-input>
						</el-form-item>

						<el-form-item label="兴趣爱好" prop="hobby">
							<el-select style="width: 30rem;" v-model="recommendData.hobby" placeholder="选择你感兴趣的标签"
								multiple clearable filterable>
								<el-option-group v-for="group in allTags" :key="group.lable" :label="group.lable">
									<el-option v-for="item in group.options" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-option-group>
							</el-select>
						</el-form-item>

						<el-form-item label="图标">
							<el-upload ref="upload" list-type="picture-card" :auto-upload="false" :limit="1"
								:on-change="fileChange" :before-upload="beforeupload" method="post" action="#">
								<template #default>
									<i class="el-icon-plus"></i>
								</template>
								<template #file="{file}">
									<div>
										<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
										<span class="el-upload-list__item-actions">
											<span v-if="!disabled" class="el-upload-list__item-delete"
												@click="handleRemove(file)">
												<i class="el-icon-delete"></i>
											</span>
										</span>
									</div>
								</template>
							</el-upload>
						</el-form-item>
						<el-form-item label="资源详情">
							<el-input style="width: 30rem;" v-model="recommendData.details"
								:autosize="{ minRows: 4, maxRows: 4 }" type="textarea"
								placeholder="详细说明该资源的使用说明需要注意的地方" clearable>
							</el-input>
						</el-form-item>
						<el-form-item>
							<el-button style="width: 12.5rem;" type="primary" @click.native="addResource()">提交
							</el-button>
						</el-form-item>


					</el-form>				
				</el-card>
			</div>
		</el-row>
	</div>
</template>
<script>
	import tags from '@/resource/tags.json';
	import {
		ref
	} from 'vue'
	import Qs from 'qs';
	import {
		ElMessage
	} from 'element-plus';
	export default {
		created() {
			// console.log(tags);
		},
		data() {
			const checkLink = (rule, value, callback) => {
				let urlRex = new RegExp(/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/);
				if (value === '') {
					callback(new Error('请输入资源链接'))
				} else if (urlRex.test(value) === false) {
					callback(new Error("请输入以http(s)开头的合法url"))
				} else {
					callback()
				}
			}
			return {
				allTags: tags,
				imageUrl: '',
				dialogImageUrl: '',
				dialogVisible: false,
				disabled: false,
				recommendFormData: new FormData(),
				recommendData: {
					title: '',
					description: '',
					link: '',
					hobby: [],
					icon: {},
					details: '',
					file: {}
				},
				rules: {
					title: [{
							required: true,
							message: '请输入资源名称',
							trigger: 'blur',
						},
						{
							max: 25,
							message: '字数不能超过25个',
							trigger: 'blur',
						},
					],
					description: [{
							required: true,
							message: '请输入资源描述',
							trigger: 'blur',
						},
						{
							max: 80,
							message: '字数不能超过80个',
							trigger: 'blur',
						},
					],
					link: [{
						validator: checkLink,
						trigger: 'blur',
					}, ],
					hobby: [{
						required: true,
						message: '请选择资源分类标签',
						trigger: 'blur',
					}, ],
				}			
			}
		},
		methods: {

			addResource() {
				this.$refs.recommendForm.validate(async (valid) => {
					if (!valid) {
						this.$messge.error("请求出错");
						return;
					};
					let that = this;
					this.recommendFormData.append("userId", localStorage.pg_username);
					this.recommendFormData.append("recommendName", this.recommendData.title);
					this.recommendFormData.append("description", this.recommendData.description);
					this.recommendFormData.append("link", this.recommendData.link);
					this.recommendFormData.append("tag", this.recommendData.hobby);
					this.recommendFormData.append("info", this.recommendData.details);
					this.$refs.upload.submit(); //提交表单
					this.$refs.upload.clearFiles(); // 清空图片的数据

					//发送请求
					this.$axios({
						url: 'http://localhost:8080/Recommend/InsertRecommend',
						method: 'post',
						transformRequest: [function(data) {
							// 对 data 进行任意转换处理
							return data
						}],
						headers: {
							'Content-Type': 'multipart/form-data',
							'token': localStorage.pg_token,
						},
						data: this.recommendFormData,
						transformResponse: [function(data) {
							// 对接收的 data 进行任意转换处理
							let result = JSON.parse(data);
							// console.log(result);
							if (result.code === 200) {
								ElMessage({
									message: '资源推荐成功，积分+5',
									type: 'success',
								});
								that.$router.go(0);
							} else {
								ElMessage({
									message: result.msg,
									type: 'error',
								});
								that.loginStatus = false;
								that.$router.go(0);
							}
							return data;
						}],
					})
					this.recommendFormData = "";
					return false;
				})
			},
			handleRemove(file) {
				this.$refs.upload.handleRemove(file);
			},
			beforeupload(file) {
				// console.log(file);
				// console.log('that.recommendFormData.get("file")',this.recommendFormData.get("file"));
				if (file !== undefined && file !== null) {
					this.recommendFormData.append("file", file); //将图片添加到formData中保存
				} else {
					let file = new File(['icon'],
						'icon.png', {
							type: 'imge/png',
						});
					this.recommendFormData.append("file", file);
				}


				return false;
			},
			fileChange(file, fileList) {
				let fileType = file.raw.type
				let fileSize = file.size
				const isJPG = (fileType === 'image/jpeg' || fileType === 'image/png')
				const isLt2M = file.size / 1024 / 1024 < 2
				this.recommendData.file = file;
				console.log(this.recommendData.file)
				if (!isJPG) {
					this.$message.error('只允许上传JPEG/JPG/PNG格式的图片')
				} else if (!isLt2M) {
					this.$message.error('图片大小不能超过2MB')
				}

				if (!(isJPG && isLt2M)) {
					this.$refs.upload.handleRemove(file);
				}
				return isJPG && isLt2M
			},
		},
	}
</script>
<style>
	.recommend-container {
		box-sizing: border-box;
		margin: 0;
		color: rgba(0, 0, 0, .85);
		font-size: 14px;
		font-variant: tabular-nums;
		line-height: 1.5715;
		list-style: none;
		font-feature-settings: "tnum", "tnum";
		position: relative;
		padding: 10px 20px;
		/* flex-wrap: wrap; */
		/* background-color: #FFF; */
	}


	.box-card {
		width: 100%;
	}

	.form-main {
		text-align: left;
	}

	.form-main-input {
		width: 30rem;
	}

	.page-content {
		background-color: #FFFFFF;
		box-sizing: border-box;
		margin: 1.5rem auto;
		height: 100%;
		width: 100%;
	}

	.page-header {
		display: flex;
		flex-direction: column;
		background-color: white;
		align-items: flex-start;
		width: 100%;
		/* margin: 0.3125rem 0.3125rem 1rem 0.3125rem; */
	}

	.page-header-heading {
		display: flex;
		justify-content: space-between;
	}

	.page-header-heading-left {
		display: flex;
		align-items: center;
		margin: 4px 0.75rem;
		overflow: hidden;
	}

	.page-header-heading-title {
		font-size: 1.375rem;
		font-weight: 600;
		margin-right: 12px;
		margin-bottom: 0;
		color: rgba(0, 0, 0, .85);
		font-weight: 600;
		font-size: 20px;
		line-height: 32px;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.page-header-content {
		padding: 0.75rem;
		word-spacing: 5px;
	}
</style>
